﻿/*                              
   Copyright 2011 Nils Kopal, Christopher Krüger, Simone Sauer, Dennis Nolte, Uni Duisburg-Essen

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace Sharebert.LinkLayerLibrary
{
    public static class Serialisation
    {
        /// <summary>
        /// Serializes the given object into XML and returns a byte array of it.
        /// </summary>
        /// <param name="o">The object that needs to be serialized</param>
        /// <param name="type">The type of the object</param>
        /// <returns>The serialization as byte array</returns>
        /// <exception cref="Sharebert.LinkLayerLibrary.SerialzationException">Error while serialzing</exception>
        public static byte[] Serialize(object o, Type type)
        {
            try
            {
                using (MemoryStream mstream = new MemoryStream())
                {
                    XmlSerializer serializer = new XmlSerializer(type);
                    serializer.Serialize(mstream, o);
                    return mstream.GetBuffer();
                }
            }
            catch (Exception ex)
            {
                throw new SerializationException("Could not serialize packet " + type.ToString(), ex);
            }
        }

        /// <summary>
        /// Deserializes the given XML serialization and returns the originating object.
        /// </summary>
        /// <param name="bytes">The byte array containing the xml serialization to deserialize</param>
        /// <param name="type">The type of the object</param>
        /// <returns>The object</returns>
        /// <exception cref="Sharebert.LinkLayerLibrary.SerialzationException">Error while deserialzing</exception>
        public static object Deserialize(byte[] bytes, Type type)
        {
            try
            {
                using (MemoryStream mstream = new MemoryStream(bytes))
                {
                    XmlSerializer serializer = new XmlSerializer(type);
                    return serializer.Deserialize(mstream);
                }
            }
            catch(Exception ex)
            {
                throw new SerializationException("Could not deserialize packet " + type.ToString(), ex);
            }
        }
    }

}
